#
# @lc app=leetcode.cn id=84 lang=python
#
# [84] 柱状图中最大的矩形
#

# @lc code=start
class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        heights.insert(0, 0)
        heights.append(0)
        stack = [0]
        result = 0
        for i in range(1, len(heights)):
            if heights[i] > heights[stack[-1]]:
                stack.append(i)

            elif heights[i] == heights[stack[-1]]:
                stack.pop()
                stack.append(i)

            else:
                while stack and heights[i] < heights[stack[-1]]:
                    max_high = heights[stack[-1]]
                    stack.pop()
                    if stack:
                        result = max((i-stack[-1]-1) * max_high, result)
                stack.append(i)
                    
        return result
        
# @lc code=end

